import clipboard from "clipboard"

export function getfilesize(size: number): string {
  if (!size) return "";
  let num = 1024.00; //byte
  if (size < num)
    return size + "B";
  if (size < Math.pow(num, 2))
    return (size / num).toFixed(2) + "KB"; //kb
  if (size < Math.pow(num, 3))
    return (size / Math.pow(num, 2)).toFixed(2) + "MB"; //M
  if (size < Math.pow(num, 4))
    return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
  return (size / Math.pow(num, 4)).toFixed(2) + "T"; //T
};

export function getMbSize(size: string | number): number {
  let num = 1024.00; //byte
  return Number(((size as number) / Math.pow(num, 2)).toFixed(2))
}

export function getFileType(str: string): string {
  const regx = /\.([^.]+)$/
  const patch = str.match(regx) || []
  return patch[1]
}

export function getFileName(str: string): string {
  const regx = /\.([^.]+)$/
  return str.replace(regx, "")
}

export function setLocal(key: string, value: any) {
  if (typeof value === "object" || Array.isArray(value)) {
    value = JSON.stringify(value);
  }
  window.localStorage.setItem(key, value)
}

export function getLocal(key: string): any {
  let result = window.localStorage.getItem(key) || ""
  if (typeof result === "object" || Array.isArray(result)) {
    result = JSON.parse(result);
  }
  return result
}

export function solveTimeStamp(time: string): number | string {
  const REGX = /(\d+[hdms])/g
  const GET_NUMBER = /\d+/g
  const matches = time.match(REGX)
  // 匹配不到，返回永久
  if (!matches) return "*";
  // 匹配得到，返回正确解构值
  let expired = Date.now()

  matches.forEach(match => {
    let day = match.match(GET_NUMBER) || []
    let num = Number(day[0])

    // 判断时间
    if (~match.indexOf("d")) {
      expired += num * 24 * 60 * 60 * 1000
    }
    else if (~match.indexOf("h")) {
      expired += num * 60 * 60 * 1000
    }
    else if (~match.indexOf("m")) {
      expired += num * 60 * 1000
    }
    else if (~match.indexOf("s")) {
      expired += num * 1000
    }
  })
  return expired
}

export function copyTxt(btnSelector: string): void {
  let board = new clipboard(btnSelector)
  board.on('success', function (e) {
    board.destroy();
  });
}

export function getExpiredTime(time: string): string {
  const reg = /-([\d|permanent]+)-/
  const matchs = time.match(reg) || []
  const expiredTime = matchs[1]
  let content = ""

  if (expiredTime != "permanent") {
    content = formatTime(Number(expiredTime))
  }

  return content
}

export function formatTime(time: number) {
  let date = new Date(time); // 初始化日期
  let year = date.getFullYear(); //获取年份
  let month = date.getMonth() + 1; // 获取月份
  let day = date.getDate(); // 获取具体日
  let hour = date.getHours(); // 获取时
  let minutes = date.getMinutes(); // 获取分
  let seconds = date.getSeconds(); // 获取秒
  return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
}
